package com.topisv.tms.rest.qimen.qmservice;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXB;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.exception.ErrorCode;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.repository.log.OrderLogDao;
import com.topisv.tms.repository.work.WorkOrderDao;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryprocess.DeliveryOrder;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryprocess.DeliveryProcess;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryprocess.Process;
import com.topisv.tms.rest.qimen.qmenum.QMOrderStatusCode;
import com.topisv.tms.rest.qimen.qmsend.QmRequestSender;
import com.topisv.tms.rest.qimen.request.RequestMethodType;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.utils.InitProperties;
import com.topisv.tms.utils.TimeUtil;

/**
 * 奇门出库流水接口 create by gaohuan 2015-05-09
 * */
@Component
@Transactional(readOnly =  false)
public class DeliveryProcessService  extends QmRequestSender<Map<String,Object>> {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private WorkOrderDao workOrderDao;
	
	@Autowired
	private OrderLogDao orderLogDao;
	
	@Transactional(readOnly = false,rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public String execute(Map<String,Object> params,RequestParams sendParams)throws PaiUException{
		EdiOrder ediOrder = (EdiOrder)params.get("ediOrder");
		String status = (String)params.get("status");
		
		
		String sendXml = "";
		if(ediOrder==null){
			logger.info("ediOrder 为空");
			return null;
		}
		// 关闭卡利亚出库流水接口
		if("KLY".equals(ediOrder.getCustomerCode())){
		    return null;
		}
		sendParams.getParams().put("customerId", ediOrder.getCustomerCode());
		try{
			DeliveryProcess dp = new DeliveryProcess();
			DeliveryOrder dOrder = new DeliveryOrder();
			
			
			
			dOrder.setDeliveryOrderCode(ediOrder.getCustomerOrdeno());
			dOrder.setDeliveryOrderId(ediOrder.getOrdeno());
			dOrder.setOrderType("JYCK");
			
			Process process = new Process();
			if("cancel".equals(status)||"cancel".equals(ediOrder.getOrderStatus())){
				process.setProcessStatus(QMOrderStatusCode.ORDER_CANCELED.getCode());
			}else {
				if("pending".equals(ediOrder.getStatus())){
					process.setProcessStatus(QMOrderStatusCode.ORDER_NEW.getCode());
				}else {
					WorkOrder workOrder = workOrderDao.findByOrder(ediOrder.getOrdeno());
					logger.info("订单当前状态:"+workOrder.getStatus());
					if(workOrder==null){
						process.setProcessStatus(QMOrderStatusCode.ORDER_NEW.getCode());
					} else {
						//由于随时可以打印所以打印状态需要传入，来发送消息
						if("print".equals(status)){
							process.setOperateInfo("仓库已打印");
							process.setProcessStatus(QMOrderStatusCode.ORDER_PRINT.getCode());
						//任务状态( 1.创建批次 2.创建任务 3.已拣货 4.已灯光拣选 9.待包装 5.已包装 6.已发货 7.已签收 8.异常)
						}else if("send".equals(status)||"6".equals(workOrder.getStatus())||"7".equals(workOrder.getStatus())||"8".equals(workOrder.getStatus())){
							process.setOperateInfo("仓库已发货");
							process.setProcessStatus(QMOrderStatusCode.ORDER_DELIVERED.getCode());
						}else if("package".equals(status)||"5".equals(workOrder.getStatus())){
							process.setOperateInfo("仓库已包装");
							process.setProcessStatus(QMOrderStatusCode.ORDER_PACKAGE.getCode());
						}else if("pick".equals(status)||"3".equals(workOrder.getStatus())||"9".equals(workOrder.getStatus())||"4".equals(workOrder.getStatus())) {
							process.setOperateInfo("仓库已拣货");
							process.setProcessStatus(QMOrderStatusCode.ORDER_PICK.getCode());
						}else if("createBatch".equals(status)||"1".equals(workOrder.getStatus())||"2".equals(workOrder.getStatus())){
							process.setOperateInfo("仓库已接单");
							process.setProcessStatus(QMOrderStatusCode.ORDER_ACCEPT.getCode());
						}
					}
					process.setOperatorCode("");
					process.setOperatorName("");
					process.setOperateTime(TimeUtil.getNowDateString());
					process.setRemark("");
					
					logger.info("本次发送流水状态:"+workOrder.getStatus()+"|"+status);
					//操作类型 (1.创建批次 2.创建任务 3.领取拣货任务  4.完成拣货任务 5.领取灯光拣选任务 6.完成灯光拣选任务  7.领取包装任务 8完成包装任务  9.领取发货任务  10.完成发货任务  11.打印单据 )
//					Map<String,String> operateTypeMapper = new HashMap<String,String>();
//					operateTypeMapper.put(QMOrderStatusCode.ORDER_CANCELED.getCode(), "");
//					operateTypeMapper.put(QMOrderStatusCode.ORDER_NEW.getCode(), "");
//					operateTypeMapper.put(QMOrderStatusCode.ORDER_PRINT.getCode(), "");
//					
//					operateTypeMapper.put("1", QMOrderStatusCode.ORDER_ACCEPT.getCode());
//					operateTypeMapper.put("2", QMOrderStatusCode.ORDER_ACCEPT.getCode());
//					operateTypeMapper.put("3", QMOrderStatusCode.ORDER_ACCEPT.getCode());
//					operateTypeMapper.put("5", QMOrderStatusCode.ORDER_ACCEPT.getCode());
//					
//					operateTypeMapper.put("4", QMOrderStatusCode.ORDER_PICK.getCode());
//					operateTypeMapper.put("6", QMOrderStatusCode.ORDER_PICK.getCode());
//					operateTypeMapper.put("7", QMOrderStatusCode.ORDER_PICK.getCode());
//					
//					operateTypeMapper.put("8", QMOrderStatusCode.ORDER_PACKAGE.getCode());
//					operateTypeMapper.put("9", QMOrderStatusCode.ORDER_PACKAGE.getCode());
//					
//					operateTypeMapper.put("10", QMOrderStatusCode.ORDER_DELIVERED.getCode());
					
					
//					List<OrderLog> orderLogList = null;
//					OrderLog currOrderLog =  null;
//					if(workOrder!=null){
//						orderLogList = orderLogDao.loadLogByOrdernoD(ediOrder.getOrdeno());
//						if(orderLogList!=null && orderLogList.size()>0){
//							currOrderLog = orderLogList.get(0);
//						}
//						for(OrderLog orderLog : orderLogList){
//							if(ediOrder.getOrdeno().equals(orderLog.getOrderno())&&
//									process.getProcessStatus().equals(operateTypeMapper.get(orderLog.getOperateType()))){
//								currOrderLog = orderLog;
//								break;
//							}
//						}
//					}
//					if(currOrderLog==null){
//						process.setOperatorCode("");
//						process.setOperateInfo("");
//					}else {
//						process.setOperatorCode(currOrderLog.getOperater().getId()+"");
//						process.setOperateInfo(currOrderLog.getAboutInfo());
//					}
					
				}
			}
			dOrder.setWarehouseCode(ediOrder.getWarehouseCode());
			
			
			dp.setDeliveryOrder(dOrder);
			dp.setProcess(process);
			
			StringWriter writer = new StringWriter();
			JAXB.marshal(dp,writer);
			sendXml = writer.toString();
			
		}catch(PaiUException e){
        	throw new PaiUException(ErrorCode.DATA_ERROR);
		}catch(Exception e){e.printStackTrace();
        	throw new PaiUException(ErrorCode.DATA_ERROR);
		}
		return sendXml;
	}
	
	@Override
	public RequestParams setupParam(RequestParams sendParams) {
		
		Map<String,String> params = new HashMap<String,String>();
		params.put("method", RequestMethodType.ORDERPROCESS_REPORT.getType());
		params.put("format", InitProperties.get("qm.format"));
		params.put("app_key", InitProperties.get("regAppKey"));
		params.put("v", InitProperties.get("qm.v"));
		params.put("sign_method", InitProperties.get("qm.sign_method"));
		params.put("customerId", "");//暂未定
		sendParams.setSecret(InitProperties.get("regAppSecret"));
		sendParams.setParams(params);
		return sendParams;
	}
}
